﻿

#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UFIDA.U9.CBO.MFG.BOM;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.Base;
using UFSoft.UBF.Business;
using UFIDA.U9.Cust.SH.SHFastShipKitItemBE;
using UFSoft.UBF.Util.DataAccess;
using UFIDA.U9.SM.SO;
using UFIDA.U9.Cust.SH.SHFastShipBE.SHFastShipBE;
using UFSoft.UBF.PL.Engine;


#endregion

namespace UFIDA.U9.Cust.SH.SHFastShipBE {

	public partial class SHFastShipLine{

		#region Custom Constructor

		#endregion

		#region before & after CUD V 
		/*	实体提交的事件顺序示例(QHELP) 主实体A 组合 非主实体B .
		/ (新增A和B两个实例)A.OnSetDefaultValue->B.OnSetDefaultValue-> B.OnValidate ->A.OnValidate ->A.OnInserting ->B.OnInserting ->产生提交SQL ->B.OnInserted ->A.OnInserted
		/ (仅修改B,A也会被修改))A.OnSetDefaultValue->B.OnSetDefaultValue-> B.OnValidate ->A.OnValidate ->A.OnUpdating ->B.OnUpdating ->产生提交SQL ->B.OnUpdated ->A.OnUpdated
		/ (删除A,B会被级联删除))A.OnDeleting ->B.OnDeleting ->产生提交SQL ->B.OnDeleted ->A.OnDeleted
		/	产生提交SQL顺序则看其外键，增修一对多先A后B，一对一先B后A。　删除一对多先B后A，一对一先A后B .
		*/	
		/// <summary>
		/// 设置默认值
		/// </summary>
		protected override void OnSetDefaultValue()
		{
			base.OnSetDefaultValue();
            if (this.Qty != this.OriginalData.Qty)
            {
                this.Weight = this.Qty * this.Item.Weight;
            }
		}
		/// <summary>
		/// before Insert
		/// </summary>
		protected override void OnInserting() {
			base.OnInserting();
			// TO DO: write your business code here...
            //this.Price = 100;
            //this.Amount = this.Qty * Price;
            
		}

		/// <summary>
		/// after Insert
		/// </summary>
		protected override void OnInserted() {
			base.OnInserted();
			// TO DO: write your business code here...
            //using (ISession session = Session.Open())
            //{
            //    //创建Kit子件并且占用库存
            //    if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            //    {
            //        this.CreateKitItem();
            //    }
            //    else
            //    {
            //        long lotid = 0;
            //        if (LotMasterKey != null) lotid = LotMasterKey.ID;
            //        ReserveQty(ItemKey.ID, WHKey.ID,lotid, Qty);
            //    }
                
            //    //更新SOLine状态
            //    this.UpdateSOLine();

            //    session.Commit();
            //}
            
		}

        /// <summary>
        /// 行预留
        /// </summary>
        /// <param name="flag">true=占用 false=释放</param>
        public void ReserveLine(bool flag)
        {
            int ratio = 1;
            if (flag == false)
                ratio = -1;

            if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            {
                SHFastShipKitItem.EntityList items = SHFastShipKitItem.Finder.FindAll("SHFastShipLine=" + this.ID, null);
                foreach (SHFastShipKitItem item in items)
                {
                    long lotid = 0;
                    if (LotMasterKey != null) lotid = LotMasterKey.ID;
                    ReserveQty(item.ItemKey.ID, item.WHKey.ID, lotid, item.Qty * ratio);
                }
            }
            else
            {
                long lotid = 0;
                if (LotMasterKey != null) lotid = LotMasterKey.ID;
                ReserveQty(this.ItemKey.ID, WHKey.ID, lotid, Qty * ratio);
            }
        }

        private void ReserveQty(long itemid,long wh,long lot,decimal qty)
        {
            //Update InvTrans_WhQoh set ResvStQtyCU=isnull(ResvStQtyCU,0)+100
            //  where ItemInfo_ItemID=1001106228127323 and Wh=1001103250302400

            if (qty == 0) return;

            ItemMaster item = ItemMaster.Finder.FindByID(itemid);
            if (item == null) throw new Exception("查找料品出错！");

            string sql = "";
            if(qty>0) sql="Update InvTrans_WhQoh set ResvStQtyCU=isnull(ResvStQtyCU,0)+" + qty.ToString();
            else if (qty < 0) sql = "Update InvTrans_WhQoh set ResvStQtyCU=isnull(ResvStQtyCU,0)" + qty.ToString();
            sql += " where 1=1";
            sql += " and ItemInfo_ItemCode='" + item.Code + "'";
            sql += " and wh=" + wh;
            if (lot > 0)
                sql += " and LotInfo_LotMaster_EntityID="+lot;
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null);
        }

		/// <summary>
		/// before Update
		/// </summary>
		protected override void OnUpdating() {
			base.OnUpdating();
			// TO DO: write your business code here...
            //this.Amount = this.Qty * Price;

		}

        /// <summary>
        /// 删除Kit套件子件
        /// </summary>
        private void DeleteKitItem()
        {
            if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            {
                SHFastShipKitItem.EntityList items = SHFastShipKitItem.Finder.FindAll("SHFastShipLine=" + this.ID, null);
                foreach (SHFastShipKitItem item in items)
                {
                    long lotid = 0;
                    if (LotMasterKey != null) lotid = LotMasterKey.ID;
                    ReserveQty(item.ItemKey.ID, item.WHKey.ID, lotid, item.Qty * -1);
                    item.Remove();
                }
            }
            
        }

        /// <summary>
        /// 创建Kit套件子件
        /// </summary>
        private void CreateKitItem()
        {
            //生成Kit件子件记录
            if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            {
                string opath = "1=1";
                opath += " and ItemMaster.Code='" + this.Item.Code + "'";
                opath += " and EffectiveDate<='" + Context.LoginDateTime + "'";
                opath += " and DisableDate>='" + Context.LoginDateTime + "'";

                BOMMaster master = BOMMaster.Finder.Find(opath, null);
                if (master == null) throw new Exception("料品" + this.Item.Code + "不存在BOM！");
                //this.BOMKey = master.Key;
                //this.BOMOrgKey = master.OrgKey;

                foreach (BOMComponent comp in master.BOMComponents)
                {
                    if (comp.IsEffective == true && comp.EffectiveDate <= Context.LoginDateTime && comp.DisableDate >= Context.LoginDateTime)
                    {
                        SHFastShipKitItem kititem = SHFastShipKitItem.Create();
                        kititem.SHFastShipLineKey = this.Key;
                        //料品依据组织需要转换
                        ItemMaster item = null;
                        if (Context.LoginOrg.Code == "1000")
                        {
                            //双虎组织不用转换
                            item = comp.ItemMaster;
                        }
                        else
                        {
                            //经销商组织需要转换
                            item = ItemMaster.Finder.Find("Org="+Context.LoginOrg.ID+" and Code='"+comp.ItemMaster.Code+"'");
                            if (item == null) throw new Exception("查找经销商组织料品失败，料品编码："+comp.ItemMaster.Code);
                           
                        }

                        kititem.ItemKey = item.Key;
                        kititem.Qty = comp.UsageQty * this.Qty;

                        //子件仓库默认逻辑
                        if (this.WHKey == this.Item.SaleInfo.ShipmentWarehouseKey)
                        {
                            kititem.WHKey = item.SaleInfo.ShipmentWarehouseKey;
                        }
                        else
                        {
                            kititem.WHKey = this.WHKey;
                        }

                        long lotid = 0;
                        if (LotMasterKey != null) lotid = LotMasterKey.ID;
                        ReserveQty(kititem.ItemKey.ID, kititem.WHKey.ID, lotid, kititem.Qty);
                    }
                }
            }
        }

        public bool KitInfoChange()
        {
            if (this.Item.ItemFormAttribute != ItemTypeAttributeEnum.Kit) return false;
            if (this.OriginalData.ItemKey == null) return true;
            if (this.ItemKey.ID != this.OriginalData.ItemKey.ID) return true;
            if (this.Qty != this.OriginalData.Qty) return true;
            if (this.WHKey.ID != this.OriginalData.WHKey.ID) return true;
            return false;
        }

		/// <summary>
		/// after Update
		/// </summary>
		protected override void OnUpdated() {
			base.OnUpdated();
			// TO DO: write your business code here...
            //using (ISession session = Session.Open())
            //{
            //    if (this.SHFastShip.DocState == FastShipDocState.DocOpen)
            //    {
            //        //开立单据修改
            //        //更新Kit子件，并占用库存
            //        if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            //        {
            //            if (KitInfoChange())
            //            {
            //                this.DeleteKitItem();
            //                this.CreateKitItem();
            //            }
            //        }
            //        else
            //        {
            //            if (ReserveInfoChange())
            //            {
            //                long lotid0 = 0;
            //                if (this.OriginalData.LotMasterKey != null) lotid0 = this.OriginalData.LotMasterKey.ID;
            //                ReserveQty(this.OriginalData.ItemKey.ID, this.OriginalData.WHKey.ID, lotid0
            //                    , this.OriginalData.Qty * -1);

            //                long lotid1 = 0;
            //                if (LotMasterKey != null) lotid1 = LotMasterKey.ID;
            //                ReserveQty(this.ItemKey.ID, this.WHKey.ID, lotid1, this.Qty);
            //            }
            //        }

            //        //更新SOLine状态
            //        this.UpdateSOLine();
            //    }
                
            //    session.Commit();
            //}
		}

        /// <summary>
        /// 更新SOLine状态
        /// </summary>
        public void UpdateSOLine()
        {
            decimal old = 0;
            decimal new1 = 0;

            if (this.SysState == ObjectState.Unchanged) return;
            if (this.SOLineKey == null) return;
            //更新SOLine状态
            if (this.SysState == ObjectState.Inserted)
            {
                old = PubTool.ToDecimal(this.SOLine.DescFlexField.PrivateDescSeg7);
                new1 = this.Qty + old;
                
            }
            else if (this.SysState == ObjectState.Updated)
            {
                if (this.Qty == this.OriginalData.Qty) return;

                old = PubTool.ToDecimal(this.SOLine.DescFlexField.PrivateDescSeg7);
                new1 = old + (this.Qty - this.OriginalData.Qty);

            }
            else if (this.SysState == ObjectState.Deleted)
            {
                old = PubTool.ToDecimal(this.SOLine.DescFlexField.PrivateDescSeg7);
                new1 = old - this.Qty;
            }

            if (new1 <= 0) new1 = 0;
            this.SOLine.DescFlexField.PrivateDescSeg7 = new1.ToString();
            if (new1 >= this.SOLine.OrderByQtyTU)
            {
                this.SOLine.Status = SODocStatusEnum.Close;
            }
            else
            {
                this.SOLine.Status = SODocStatusEnum.Approved;
            }
            foreach (SOShipline line in this.SOLine.SOShiplines)
            {
                line.Status = this.SOLine.Status;
            }
        }

        public bool ReserveInfoChange()
        {
            if (this.OriginalData.ItemKey == null) return true;
            if (this.OriginalData.ItemKey.ID != this.ItemKey.ID) return true;
            if (this.OriginalData.WHKey.ID != this.WHKey.ID) return true;
            if (this.OriginalData.Qty != this.Qty) return true;
            return false;
        }


		/// <summary>
		/// before Delete
		/// </summary>
		protected override void OnDeleting() {
			base.OnDeleting();
			// TO DO: write your business code here...
		}

		/// <summary>
		/// after Delete
		/// </summary>
		protected override void OnDeleted() {
			base.OnDeleted();
			// TO DO: write your business code here...
            //using (ISession session = Session.Open())
            //{
            //    //创建Kit子件并且占用库存
            //    if (this.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            //    {
            //        this.DeleteKitItem();
            //    }
            //    else
            //    {
            //        long lotid = 0;
            //        if (LotMasterKey != null) lotid = LotMasterKey.ID;
            //        ReserveQty(this.ItemKey.ID, this.WHKey.ID, lotid, this.Qty * -1);
            //    }

            //    //更新SOLine状态
            //    this.UpdateSOLine();
            //    session.Commit();
            //}
		}

		/// <summary>
		/// on Validate
		/// </summary>
		protected override void OnValidate() {
			base.OnValidate();
			this.SelfEntityValidator();
			// TO DO: write your business code here...

            //通过界面标红处理，不再抱错
            //if (this.AvailableQty < this.Qty) throw new Exception("行号："+this.DocLineNo+" 料号："+this.Item.Code+"库存可用量不足！");
            if (this.UOMKey == null || this.UOMKey.ID <= 0) throw new Exception("行号："+this.DocLineNo+"数据错误，请检查基础数据设置！");

            if (this.SHFastShip.SaleWHKey != null && this.SOLineKey != null
                && this.SHFastShip.SaleWH.Code != this.SOLine.SO.DescFlexField.PubDescSeg23)
            {
                throw new Exception("行号：" + this.DocLineNo + " 销售订单的总经销仓与出货单总经销仓不同，不能保存！");
            }

            if (!string.IsNullOrEmpty(this.Item.DescFlexField.PrivateDescSeg1))
            {
                if (PubTool.IsNum(this.Item.DescFlexField.PrivateDescSeg1))
                {
                    int num = 1;
                    try
                    {
                        num = PubTool.ToInt(this.Item.DescFlexField.PrivateDescSeg1);
                    }
                    catch
                    {
                        throw new Exception("行号：" + this.DocLineNo + "料品：" + this.Item.Name +" 料品系数出错，请维护该系数！");
                    }

                    if (this.Qty % num > 0) throw new Exception("行号：" + this.DocLineNo + "料品：" + this.Item.Name + "数量必须是[" + num + "]的倍数！");
                    
                }
            }
		}

        

        #endregion

        #region 异常处理，开发人员可以重新封装异常
        public override void DealException(Exception e)
        	{
          		base.DealException(e);
          		throw e;
        	}
		#endregion

		#region  扩展属性代码区
		
		#endregion

		#region CreateDefault
		
		private  static SHFastShipLine CreateDefault_Extend(UFIDA.U9.Cust.SH.SHFastShipBE.SHFastShip parentEntity) {
			//TODO delete next code and add your custome code here
			throw new NotImplementedException () ;
		}
	    		
		#endregion 






		#region Model Methods
		#endregion		
	}
}
